package cn.hchaojie.camp.day08;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.junit.Test;

import cn.hchaojie.camp.day07.Employee;

public class DemoListSort {
	@Test
	public void testSort() {
		int[] score = {55, 32, 88, 60, 100, 99};
		
		Arrays.sort(score);
		
		System.out.println(Arrays.toString(score));
		
		String[] strs = {"aaa", "aa"};
		// 使用一个匿名内部类，来实现比较算法
		Arrays.sort(strs, new Comparator<String>() {
			public int compare(String o1, String o2) {
				return 0;
			}
		});
	}
	
	@Test
	public void testListSort() {
		List<String> list = Arrays.asList("java", "c++", "javascript", "swift", "python");
		
		Collections.sort(list);
		
		for (String item : list) {
			System.out.println(item);
		}
		
		// List 类型  class type
		// List<Employee> 泛型 generic type
		
		List<Employee> list2 = Arrays.asList(
			new Employee("java", 18),
			new Employee("c++", 28),
			new Employee("javascript", 17),
			new Employee("swift", 6),
			new Employee("python", 20)
		);
		
		// 实现一个自定义元素集合的排序，有两种方式
		// ①：sort的时候，提供一个比较器 Comparator
		Collections.sort(list2, new Comparator<Employee>() {
			// 根据年纪排序
			@Override
			public int compare(Employee o1, Employee o2) {
				// 排到后面，需要返回一个正数
//				if (o1.getAge() > o2.getAge()) {
//					return 1;
//				} else if (o1.getAge() < o2.getAge()) {
//					return -1;
//				}
//				
//				return 0;
				
				return o1.getAge() - o2.getAge();
			}
		});
		
		for (Employee item : list2) {
			System.out.println(item);
		}
		
		Collections.sort(list2, new Comparator<Employee>() {
			// 根据名字排序
			@Override
			public int compare(Employee o1, Employee o2) {
				return o1.getName().compareTo(o2.getName());
			}
		});
		
		for (Employee item : list2) {
			System.out.println(item);
		}
		
		// 排序的第二种方式
		// ② 让元素实现Comparable接口
		Collections.sort(list2);
		for (Employee item : list2) {
			System.out.println(item);
		}
		
	}
	
	@Test
	public void testAdd() {
		List<String> strs = new ArrayList<>();
		
		String s1 = "abc";
		
		strs.add(s1);
		strs.add(s1);
		strs.add(s1);
		
		System.out.println(strs.size());
		
		// list集合里面放的是对象的引用
		List<Employee> employee = new ArrayList<>();
		Employee e = new Employee("", 18);
		employee.add(e);
		employee.add(e);
		employee.add(e);
		
		e.setName("c++");
		
		for (Employee item : employee) {
			System.out.println(item);
		}
	}
	
	@Test
	public void testAdd2() {
		List<String> strs = new ArrayList<>();
		
		strs.add("java");
		strs.add("c++");
		strs.add("d");
		
		for (String s : strs) {
			System.out.println(s);
		}
	}
}
